/**
 * Copyright (c) 2012,USTC E-BUSINESS TECHNOLOGY CO.LTD All Rights Reserved.
 */

package com.cmcc.zysoft.infocollection.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.cmcc.zysoft.infocollection.common.BaseController;
import com.cmcc.zysoft.infocollection.model.News;
import com.cmcc.zysoft.infocollection.model.ReadNews;
import com.cmcc.zysoft.infocollection.model.SystemUser;
import com.cmcc.zysoft.infocollection.service.NoticePcService;
import com.cmcc.zysoft.infocollection.service.ReadNoticeService;
import com.cmcc.zysoft.spring.security.model.User;
import com.cmcc.zysoft.spring.security.util.SecurityContextUtil;
import com.cmcc.zysoft.sysmanage.service.SystemUserPCService;
import com.starit.common.dao.support.Pagination;

/**
 * @author jin.congshan
 * @date 2013-1-8 下午7:50:20
 */
@Controller
@RequestMapping("/pc/notice")
public class NoticeController extends BaseController{

	@Autowired
	private NoticePcService noticePcService;
	@Autowired
	private ReadNoticeService readNoticeService;
	@Autowired
	private SystemUserPCService systemUserService;
	
	/**
	 * 
	 * @Description: 通知公告列表页面
	 * @author jin.congshan
	 * @date 2013-1-9 下午7:54:19
	 * @return
	 *
	 */
	@RequestMapping("/noticeList.htm")
	public String noticeList(){
		return "/notice/noticeList";
	}
	
	/**
	 * 
	 * @Description: 获取各通知公告条数
	 * @author jin.congshan
	 * @date 2013-1-9 下午7:54:08
	 * @return
	 *
	 */
	@RequestMapping(value = "/getNoticeCount.htm", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> getNoticeCount(String newsType){
		User user = SecurityContextUtil.getCurrentUser();
		return this.noticePcService.getUserNoticeCount(user.getUserId(), newsType);
	}
	
	/**
	 * 
	 * @Description: 获取通知公告分页列表数据
	 * @author jin.congshan
	 * @date 2013-1-9 下午7:41:02
	 * @param code
	 * @param search 查询
	 * @param page
	 * @param rows
	 * @return
	 *
	 */
	@RequestMapping(value = "/getNoticePageData.htm", method = RequestMethod.POST)
	@ResponseBody
	public Pagination<?> getNoticePageData(String code, String search, int page,int rows){
		if(StringUtils.isBlank(code)){
			code = "0";
		}
		User user = SecurityContextUtil.getCurrentUser();
		return this.noticePcService.getNoticePageData(user.getUserId(), code, search, page, rows);
	}
	
	/**
	 * 
	 * @Description: 通知公告列表页面
	 * @author jin.congshan
	 * @date 2013-1-9 下午7:54:19
	 * @return
	 *
	 */
	@RequestMapping("/addNotice.htm")
	public String addNotice(){
		return "/notice/addNotice";
	}
	
	/**
	 * 
	 * @Description: 验证该公司是否已经存在此标题的公告 
	 * @author jin.congshan
	 * @date 2013-1-10 下午8:20:30
	 * @param title
	 * @return
	 *
	 */
	@RequestMapping(value = "/checkNoticeTitle.htm", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject checkNoticeTitle(String title, String newsId, String newsType){
		JSONObject result = new JSONObject();
		result.put("error_code", 1);
		User sessionUser = SecurityContextUtil.getCurrentUser();
		SystemUser user = this.systemUserService.getEntity(sessionUser.getUserId());
//		int count = this.noticePcService.checkNoticeName(newsId, user.getCompany().getCompanyId(), title, newsType);
		int count = this.noticePcService.checkNoticeName(newsId, user.getCompanyId(), title, newsType);
		if(0 == count){
			result.put("error_code", 0);
		}
		return result;
	}
	
	/**
	 * 
	 * @Description: 保存通知公告信息
	 * @author jin.congshan
	 * @date 2013-1-10 下午7:39:45
	 * @param news 通知公告对象
	 * @return
	 *
	 */
	@RequestMapping(value = "/saveNoticeInfo.htm", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String saveNoticeInfo(News news){
		JSONObject result = new JSONObject();
		User sessionUser = SecurityContextUtil.getCurrentUser();
		SystemUser user = this.systemUserService.getEntity(sessionUser.getUserId());
//		news.setReleaseDate(new Date());
//		news.setReleaseMan(user.getUserId());
//		news.setCompanyId(user.getCompany().getCompanyId());
//		news.setCompanyId(user.getCompanyId());
		if(StringUtils.isBlank(news.getNewsId())){
			this.noticePcService.insertEntity(news);
		} else {
			this.noticePcService.updateEntity(news);
		}
		// 非草稿，初始化阅读信息
		if(StringUtils.isNotBlank(news.getState()) && "1".equals(news.getState())){
//			List<SystemUser> list = this.systemUserService.findByNamedParam(new String[]{"delFlag", "company.companyId"}, new String[]{"0", user.getCompany().getCompanyId()});
			List<SystemUser> list = this.systemUserService.findByNamedParam(new String[]{"delFlag", "company.companyId"}, new String[]{"0", user.getCompanyId()});
			if(null != list && list.size() > 0){
				SystemUser a = null;
				for (int i = 0; i < list.size(); i++) {
					a = list.get(i);
					ReadNews readNews = new ReadNews();
					readNews.setNewsId(news.getNewsId());
//					readNews.setNewsType("0");
					readNews.setReadNum(0);
					readNews.setUserId(a.getUserId());
					this.readNoticeService.insertEntity(readNews);
				}
			}
		}
		result.put("error_code", 0);
		return result.toJSONString();
	}
	
	/**
	 * 
	 * @Description : KindEditor上传图片专用 
	 * @author jin.congshan
	 * @date 2013-1-10 下午9:25:58
	 * @param imgFile 图片文件
	 * @param request
	 * @return 成功标识、图片地址
	 *
	 */
	@RequestMapping(value = "/uploadImage.htm", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest request) {
		User sessionUser = SecurityContextUtil.getCurrentUser();
		SystemUser user = this.systemUserService.getEntity(sessionUser.getUserId());
		JSONObject result = new JSONObject();
		try {
			if (null != imgFile && !imgFile.isEmpty()) {
				String orginFileName = imgFile.getOriginalFilename();
				String realPath = request.getSession().getServletContext().getRealPath("/resources/image/upload");
				realPath = realPath + File.separator + user.getUserId();
				File file = new File(realPath);
				if (!file.exists()) {
					file.mkdirs();
				}
				String fileName = (String.valueOf(System.currentTimeMillis()))+ orginFileName.substring(orginFileName.indexOf("."));
				String path = realPath + File.separator + fileName;
				File file1 = new File(path);
				FileUtils.copyInputStreamToFile(imgFile.getInputStream(), file1);
				path = "/resources/image/upload/"+user.getUserId()+"/"+ fileName;
				result.put("error", 0);
				result.put("url", path);
			}
		} catch (Exception e) {
			result.put("error", 1);
		}
		return result.toJSONString();
	}
	
	/**
	 * 
	 * @Description : 删除选中的草稿状态的通知公告
	 * @author jin.congshan
	 * @date 2013-1-10 下午9:27:32
	 * @param ids
	 * @return
	 *
	 */
	@RequestMapping(value = "/deleteNotice.htm", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deleteNotice(String[] ids){
		JSONObject result = new JSONObject();
		String str  = "'" + StringUtils.join(ids, "','") + "'";
		String names = this.noticePcService.getNoticeNameStr(str, "2");
		if(StringUtils.isNotBlank(names)){
			result.put("error", 1);
			result.put("message", names);
			return result;
		}
		this.noticePcService.deleteNotice(str);
		result.put("error", 0);
		return result;
	}
	
	/**
	 * 
	 * @Description ：查看通知公告详情
	 * @author jin.congshan
	 * @date 2013-1-11 下午8:44:27
	 * @param newsId 通知公告ID
	 * @return
	 *
	 */
	@RequestMapping("/noticeDetail/{newsId}.htm")
	@Transactional
	public String noticeDetail(@PathVariable String newsId, ModelMap modelMap){
		User sessionUser = SecurityContextUtil.getCurrentUser();
		News news = this.noticePcService.getEntity(newsId);
		List<ReadNews> list = this.readNoticeService.findByNamedParam(new String[]{"newsId", "userId"}, new Object[]{newsId, sessionUser.getUserId()});
		ReadNews readNews = list.get(0);
		readNews.setReadNum(readNews.getReadNum() + 1);
		readNews.setReadDate(new Date());
		this.readNoticeService.updateEntity(readNews);
//		SystemUser user = this.systemUserService.getEntity(news.getReleaseMan());
		modelMap.put("news", news);
		modelMap.put("count", readNews.getReadNum());
//		modelMap.put("userName", user.getUserName());
		
		return "/notice/noticeDetail";
	}
	
	/**
	 * 
	 * @Description ：编辑通知公告信息
	 * @author jin.congshan
	 * @date 2013-1-13 下午3:09:40
	 * @param modelMap
	 * @param newsId
	 * @return
	 *
	 */
	@RequestMapping("/noticeEdit/{newsId}.htm")
	public String noticeEdit(ModelMap modelMap, @PathVariable String newsId){
		News news = this.noticePcService.getEntity(newsId);
		modelMap.put("news", news);
		return "/notice/noticeEdit";
	}
	
	/**
	 * 查找市场信息反馈的图片
	 * @param newsId
	 * @return
	 */
	@RequestMapping("/imageAddr.htm")
	@ResponseBody
	public List<Map<String, Object>> getImages(String newsId){
		return this.noticePcService.getImgs(newsId);
	}
}
